package it.univaq.di.helpdesk.presentation;

import it.univaq.di.helpdesk.business.common.HelpDeskServiceFactory;
import it.univaq.di.helpdesk.business.common.TicketService;
import it.univaq.di.helpdesk.business.model.Attachment;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;

public class ManageDownloadAction extends DownloadAction {
	
	protected class ByteArrayStreamInfo implements StreamInfo {
        
        protected String contentType;
        protected byte[] bytes;
        
        public ByteArrayStreamInfo(String contentType, byte[] bytes) {
            this.contentType = contentType;
            this.bytes = bytes;
        }
        
        public String getContentType() {
            return contentType;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(bytes);
        }
    }

	@Override
	protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		HelpDeskServiceFactory factory = HelpDeskServiceFactory.getInstance();
		TicketService service = factory.getTicketService();
		
		Attachment attachment = service.getAttachmentById(Integer.parseInt(request
				.getParameter("attachmentID")));
		
		response.setHeader("Content-Description","File Transfer");
		response.setHeader("Content-disposition", 
                "attachment; filename=" + attachment.getFileName());
		response.setHeader("Content-Transfer-Encoding", "binary");
		response.setHeader("Expires", "0");
		response.setHeader("Cache-Control", 
				"must-revalidate, post-check=0, pre-check=0");
		response.setHeader("Pragma", "public");
		response.setHeader("Content-Length", 
				Integer.toString(attachment.getFileSize()));
		
		return new ByteArrayStreamInfo(attachment.getFileContentType(),
				attachment.getAttachmentData().getFileData());
	}
}
